/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.services.project;

import cn.easyplatform.EasyPlatformWithLabelKeyException;
import cn.easyplatform.contexts.RecordContext;
import cn.easyplatform.dao.DaoFactory;
import cn.easyplatform.dao.MessageDao;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.vos.admin.CacheVo;
import cn.easyplatform.services.IProjectService;
import cn.easyplatform.services.IResourceHandler;
import cn.easyplatform.type.ModeType;
import org.apache.shiro.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.*;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
class ResourceHandlerImpl implements IResourceHandler {

    private static final Logger log = LoggerFactory.getLogger(ResourceHandlerImpl.class);

    private IProjectService ps;

    private Map<String, Cache<Serializable, String>> caches;

    private boolean enabled;

    ResourceHandlerImpl(IProjectService ps) {
        this.ps = ps;
        this.enabled = ps.getEntity().getMode() == ModeType.ONLINE;
        this.caches = new HashMap<String, Cache<Serializable, String>>();
        for (String lang : ps.getLanguages()) {
            Cache<Serializable, String> cache = ps.getCache("i18:" + lang);
            this.caches.put(lang, cache);
        }
        load();
    }

    @Override
    public synchronized int load() {
        if (enabled) {
            for (Cache<Serializable, String> cache : caches.values())
                cache.clear();
            MessageDao dao = DaoFactory.createMessageDao(ps.getDataSource());
            StringBuilder sb = new StringBuilder();
            sb.append("select code,");
            Iterator<String> itr = ps.getLanguages().iterator();
            while (itr.hasNext()) {
                String lang = itr.next();
                sb.append(lang);
                if (itr.hasNext())
                    sb.append(",");
            }
            sb.append(" from sys_message_info");
            List<String[]> rs = dao.selectList(sb.toString());
            for (String[] as : rs) {
                String code = as[0];
                itr = ps.getLanguages().iterator();
                int index = 1;
                while (itr.hasNext()) {
                    String lang = itr.next();
                    if (as[index] == null)
                        as[index] = "";
                    this.caches.get(lang).put(code, as[index++]);
                }
            }
            return rs.size();
        }
        return 0;
    }

    @Override
    public String getMessage(final String code, RecordContext rc) {
        String language = null;
        if (rc != null)
            language = rc.getParameterAsString("726");
        if (language == null)
            language = ps.getLanguages().get(0);
        if (!enabled) {
            String[] result = getMessage(code);
            if (result == null)
                throw new EasyPlatformWithLabelKeyException(
                        "easyplatform.app.message.not.found", code);
            int index = 0;
            String label = null;
            for (String lang : ps.getLanguages()) {
                if (language.equals(lang)) {
                    label = result[index];
                    break;
                }
                index++;
            }
            if (rc != null && label != null) {
                List<Object> args = new ArrayList<Object>();
                for (int i = 755; i < 759; i++) {
                    Object arg = rc.removeParameter(String.valueOf(i));
                    if (arg != null)
                        args.add(arg);
                }
                return MessageFormat.format(label, args.toArray());
            }
            return label;
        }
        try {
            Cache<Serializable, String> cache = caches.get(language);
            if (cache == null) {
                cache = caches.get(ps.getLanguages().get(0));
                if (cache == null) {
                    load();// 重新加载资源
                    cache = caches.get(language);
                    if (cache == null)
                        cache = caches.get(ps.getLanguages().get(0));
                }
            }
            String label = cache.get(code);
            if (label == null) {
                String[] result = getMessage(code);
                if (result == null)
                    throw new EasyPlatformWithLabelKeyException(
                            "easyplatform.app.message.not.found", code);
                int index = 0;
                for (String lang : ps.getLanguages()) {
                    caches.get(lang).put(code, result[index]);
                    if (language.equals(lang))
                        label = result[index];
                    index++;
                }
            }
            if (rc != null && label != null) {
                List<Object> args = new ArrayList<Object>();
                for (int i = 755; i < 759; i++) {
                    Object arg = rc.removeParameter(String.valueOf(i));
                    if (arg != null)
                        args.add(arg);
                }
                return MessageFormat.format(label, args.toArray());
            }
            return label;
        } catch (Exception ex) {
            if (ex instanceof EasyPlatformWithLabelKeyException)
                throw (EasyPlatformWithLabelKeyException) ex;
            if (log.isWarnEnabled())
                log.warn("getLabel :" + code, ex);
            return null;
        }
    }

    private String[] getMessage(String code) {
        MessageDao dao = DaoFactory.createMessageDao(ps.getDataSource());
        StringBuilder sb = new StringBuilder();
        sb.append("select ");
        Iterator<String> itr = ps.getLanguages().iterator();
        while (itr.hasNext()) {
            String lang = itr.next();
            sb.append(lang);
            if (itr.hasNext())
                sb.append(",");
        }
        sb.append(" from sys_message_info").append(" where code=?");
        return dao.select(sb.toString(), code);
    }

    public String getLabel(String language, String code) {
        MessageDao dao = DaoFactory.createMessageDao(ps.getDataSource());
        StringBuilder sb = new StringBuilder();
        sb.append("select ").append(language)
                .append(" from sys_message_info where code=?");
        return dao.selectOne(sb.toString(), code);
    }

    @Override
    public void remove(String code) {
        Iterator<String> itr = ps.getLanguages().iterator();
        while (itr.hasNext()) {
            String lang = itr.next();
            Cache<Serializable, String> cache = caches.get(lang);
            if (cache != null)
                cache.remove(code);
        }
    }

    @Override
    public String getLabel(String code) {
        return getMessage(code, null);
    }

    @Override
    public Map<String, String> getLabels(String language) {
        if (!enabled) {
            StringBuilder sb = new StringBuilder("select code,");
            sb.append(language).append(
                    " from sys_message_info");
            MessageDao dao = DaoFactory.createMessageDao(ps.getDataSource());
            List<String[]> rs = dao.selectList(sb.toString());
            Map<String, String> map = new HashMap<String, String>();
            for (String[] as : rs)
                map.put(as[0], as[1]);
            return map;
        } else {
            Cache<Serializable, String> cache = caches.get(language);
            if (cache == null)
                throw new EasyPlatformWithLabelKeyException(
                        "easyplatform.i18n.language.support", language);
            Map<String, String> m = new HashMap<String, String>();
            for (Serializable key : cache.keys())
                m.put(key.toString(), cache.get(key));
            return m;
        }
    }

    @Override
    public int getSize() {
        if (enabled) {
            Cache<Serializable, String> cache = caches.get(ps.getLanguages().get(0));
            if (cache != null)
                return cache.size();
        }
        return 0;
    }

    @Override
    public synchronized void destory() {
        for (Map.Entry<String, Cache<Serializable, String>> entry : caches.entrySet()) {
            entry.getValue().clear();
            ps.removeCache("i18:" + entry.getKey());
        }
        caches.clear();
    }

    @Override
    public List<CacheVo> getList() {
        if (enabled) {
            Cache<Serializable, String> cache = caches.get(ps.getLanguages().get(0));
            List<CacheVo> tmp = new ArrayList<CacheVo>(cache.size());
            for (Serializable key : cache.keys())
                tmp.add(new CacheVo(key.toString(), cache.get(key)));
            return tmp;
        } else
            return Collections.emptyList();
    }

    @Override
    public void setEnabled(boolean enabled) {
        if (this.enabled != enabled) {
            this.enabled = enabled;
            if (!this.enabled)
                reset();
        }
    }

    @Override
    public void reset() {
        Iterator<String> itr = ps.getLanguages().iterator();
        while (itr.hasNext()) {
            String lang = itr.next();
            Cache<Serializable, String> cache = caches.get(lang);
            if (cache != null)
                cache.clear();
        }
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}
